import subprocess
import time

# 启动一个外部进程，例如 `notepad.exe`（Windows中的记事本应用）
proc = subprocess.Popen(['calc.exe'])

# 为了示范，等待5秒
time.sleep(5)

# 终止进程

import win32api
import win32con
# import win32process
import win32com.client

def terminate_process_by_name(process_name):
    # 获取所有运行的进程
    WMI = win32com.client.GetObject('winmgmts:')
    processes = WMI.ExecQuery(f'SELECT * FROM Win32_Process WHERE Name="{process_name}"')

    for process in processes:
        process_id = process.Properties_('ProcessId').Value
        try:
            handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, process_id)
            win32api.TerminateProcess(handle, -1)
            win32api.CloseHandle(handle)
        except Exception as e:
            print(f"Failed to terminate {process_name} with PID {process_id}. Error: {e}")

# 使用方法
terminate_process_by_name("CalculatorApp.exe")
